package com.gulimall.seckill.service.impl;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.common.to.mq.SeckillOrderTo;
import com.common.utils.R;
import com.common.vo.MemberRespVo;
import com.gulimall.seckill.feign.CouponFeign;
import com.gulimall.seckill.feign.ProductFeign;
import com.gulimall.seckill.interceptor.LoginUserInterceptor;
import com.gulimall.seckill.service.SeckillService;
import com.gulimall.seckill.to.SeckillSkuRedisTo;
import com.gulimall.seckill.vo.SeckillSessionWithSkus;
import com.gulimall.seckill.vo.SkuInfoVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Service
@Slf4j
public class SeckillServiceImpl implements SeckillService {

    @Autowired
    CouponFeign couponFeign;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    ProductFeign productFeign;

    @Autowired
    RedissonClient redissonClient;

    @Autowired
    RabbitTemplate rabbitTemplate;

    private final String SESSSIONS_CACHE_PREFIX = "seckill:sessions";
    private final String SKUKILL_CACHE_PREFIX = "seckill:skus";
    private final String SKU_STOCK_SEMAPHORE = "seckill:stock:";

    @Override
    public void uploadSeckillSkuLatest3Days() {

        R session = couponFeign.getLates3DaySession();

        if (session.getCode() == 0) {

            List<SeckillSessionWithSkus> data = session.getData(new TypeReference<List<SeckillSessionWithSkus>>() {
            });

            saveSessionInfos(data);

            saveSessionSkuInfos(data);
        }
    }

    public List<SeckillSkuRedisTo> blockHandler(BlockException e) {
        log.error("getCurrentSeckillSkusResource 被限流了 ....");
        return null;
    }

    @SentinelResource(value = "getCurrentSeckillSkusResource", blockHandler = "blockHandler")
    @Override
    public List<SeckillSkuRedisTo> getCurrentSeckillSkus() {

        long time = new Date().getTime();
        try (Entry entry = SphU.entry("seckillSkus")) {
            Set<String> keys = redisTemplate.keys(SESSSIONS_CACHE_PREFIX + "*");
            for (String key : keys) {
                String replace = key.replace(SESSSIONS_CACHE_PREFIX, "");
                String[] s = replace.split("_");
                long start = Long.parseLong(s[0]);
                long end = Long.parseLong(s[1]);
                if (start <= time && time <= end) {
                    List<String> range = redisTemplate.opsForList().range(key, -100, 100);
                    BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
                    List<String> list = hashOps.multiGet(range);
                    if (list != null) {
                        List<SeckillSkuRedisTo> collect = list.stream().map(item -> {
                            SeckillSkuRedisTo redis = JSON.parseObject((String) item, SeckillSkuRedisTo.class);

                            return redis;
                        }).collect(Collectors.toList());
                        return collect;
                    }
                    break;
                }
            }
        } catch (BlockException e) {
            log.error("资源被限流", e.getMessage());
        }
        return null;
    }

    @Override
    public SeckillSkuRedisTo getSkuSeckillInfo(Long skuId) {

        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);

        Set<String> keys = hashOps.keys();

        if (keys != null && keys.size() > 0) {
            String regx = "\\d_" + skuId;
            for (String key : keys) {
                if (Pattern.matches(regx, key)) {

                    String json = hashOps.get(key);

                    SeckillSkuRedisTo redisTo = JSON.parseObject(json, SeckillSkuRedisTo.class);

                    long DateTime = new Date().getTime();
                    if (DateTime >= redisTo.getStartTime() && DateTime <= redisTo.getEndTime()) {
                    } else {
                        redisTo.setRandomCode(null);
                    }
                    return redisTo;
                }
            }
        }

        return null;
    }

    @Override
    public String secKill(String killId, String key, Integer num) {

        long s1 = System.currentTimeMillis();

        MemberRespVo respVo = LoginUserInterceptor.loginUser.get();

        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);

        String json = hashOps.get(killId);
        if (StringUtils.isEmpty(json)) {
            return null;
        } else {
            SeckillSkuRedisTo redisTo = JSON.parseObject(json, SeckillSkuRedisTo.class);

            long time = new Date().getTime();

            long ttl = redisTo.getEndTime() - time;

            if (time >= redisTo.getStartTime() && time <= redisTo.getEndTime()) {

                String randomCode = redisTo.getRandomCode();
                String skuId = redisTo.getPromotionSessionId() + "_" + redisTo.getSkuId();
                if (randomCode.equals(key) && killId.equals(skuId)) {

                    if (num <= Integer.parseInt(redisTo.getSeckillLimit().toString())) {
                        String redisKey = respVo.getId() + "_" + skuId;
                        Boolean aBoolean = redisTemplate.opsForValue().setIfAbsent(redisKey, num.toString(), ttl, TimeUnit.MILLISECONDS);
                        if (aBoolean) {

                            RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHORE + randomCode);


                            boolean b = semaphore.tryAcquire(num);
                            if (b) {
                                String timeId = IdWorker.getTimeId();

                                SeckillOrderTo orderTo = new SeckillOrderTo();
                                orderTo.setOrderSn(timeId);
                                orderTo.setMemberId(respVo.getId());
                                orderTo.setNum(num);
                                orderTo.setPromotionSessionId(redisTo.getPromotionSessionId());
                                orderTo.setSeckillPrice(redisTo.getSeckillPrice());
                                orderTo.setSkuId(redisTo.getSkuId());
                                rabbitTemplate.convertAndSend("order-event-exchange", "order-seckill.order", orderTo);

                                long s2 = System.currentTimeMillis();
                                log.info("秒杀创建耗时：{}", (s2 - s1));
                                return timeId;
                            }
                            return null;
                        } else {
                            return null;
                        }
                    }

                } else {
                    return null;
                }
            } else {
                return null;
            }
        }

        return null;
    }

    public void saveSessionInfos(List<SeckillSessionWithSkus> sesssions) {
        if (sesssions != null && sesssions.size() > 0) {
            sesssions.stream().forEach(sesssion -> {
                long startTime = sesssion.getCreateTime().getTime();
                long endTime = sesssion.getEndTime().getTime();
                String key = SESSSIONS_CACHE_PREFIX + startTime + "_" + endTime;
                Boolean hasKey = redisTemplate.hasKey(key);
                if (!hasKey) {
                    List<String> collect = sesssion.getRelationSkus().stream().map(item -> item.getPromotionSessionId() + "_" + item.getSkuId().toString()).collect(Collectors.toList());
                    redisTemplate.opsForList().leftPushAll(key, collect);
                }
            });
        }
    }

    public void saveSessionSkuInfos(List<SeckillSessionWithSkus> sesssions) {
        if (sesssions != null && sesssions.size() > 0) {
            sesssions.stream().forEach(sesssion -> {
                BoundHashOperations<String, Object, Object> hashOps = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
                sesssion.getRelationSkus().stream().forEach(seckillSkuVo -> {
                    String toekn = UUID.randomUUID().toString().replace("-", "");

                    if (!hashOps.hasKey(seckillSkuVo.getPromotionSessionId().toString() + "_" + seckillSkuVo.getSkuId().toString())) {
                        SeckillSkuRedisTo redisTo = new SeckillSkuRedisTo();

                        R skuInfo = productFeign.getSkuInfo(seckillSkuVo.getSkuId());
                        System.out.println(skuInfo.getCode());
                        if (skuInfo.getCode() == 0) {
                            SkuInfoVo skuInfoVo = skuInfo.getData("skuInfo", new TypeReference<SkuInfoVo>() {
                            });
                            redisTo.setSkuInfoVo(skuInfoVo);
                        }
                        BeanUtils.copyProperties(seckillSkuVo, redisTo);

                        redisTo.setStartTime(sesssion.getStartTime().getTime());
                        redisTo.setEndTime(sesssion.getEndTime().getTime());

                        redisTo.setRandomCode(toekn);

                        String jsonString = JSON.toJSONString(redisTo);
                        hashOps.put(seckillSkuVo.getPromotionSessionId().toString() + "_" + seckillSkuVo.getSkuId().toString(), jsonString);

                        RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHORE + toekn);
                        semaphore.trySetPermits(Integer.parseInt(seckillSkuVo.getSeckillCount().toString()));
                    }
                });
            });
        }
    }
}
